package com.wangjiyuan.shiwupai.ui_food.food_class;

import android.animation.Animator;
import android.animation.AnimatorInflater;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.wangjiyuan.shiwupai.R;
import com.wangjiyuan.shiwupai.base.BaseActivity;
import com.wangjiyuan.shiwupai.base.BaseApplication;
import com.wangjiyuan.shiwupai.base.base_map.BaseMap;
import com.wangjiyuan.shiwupai.bean.first_food.FoodBean;
import com.wangjiyuan.shiwupai.bean.first_food.FoodClassBean;
import com.wangjiyuan.shiwupai.bean.first_food.FoodSortBean;
import com.wangjiyuan.shiwupai.config.food.FoodConstant;
import com.wangjiyuan.shiwupai.ui_food.food_class.adapter.FoodClassRecAdapter;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.wangjiyuan.shiwupai.base.BaseApplication.animationDrawable;

/**
 * 食物百科分类的详情列表
 */

public class FoodClassActivity extends BaseActivity implements FoodClassContract.IFoodClassView, View.OnClickListener {
//    private Context mContext = this;
    private Map<String, String> map = BaseMap.baseMap();
    private FoodBean.GroupBean.CategoriesBean categoriesBean;
    private int pageNum=1;
    private String kind = "group", id = "1", order_by = "1", page = "1", order_asc = "0";
    private FoodClassPresenter foodClassPresenter;

    private Toolbar toolBar_foodClass;
    private TextView textView_sort, textView_order;
    private ImageView imageView_sortDown;
    private Animator animatorUp, animatorDown;
    private boolean isOrder = false;
    private RecyclerView recyclerView_foodClass;
    private List<FoodClassBean.FoodsBean> foodsBeanList = new ArrayList<>();
    private LinearLayoutManager linearLayoutManager;
    private FoodClassRecAdapter foodClassRecAdapter;
    private ImageView imageView_gif;

    private View view;
    private PopupWindow popupWindow;
    private GridLayout gridLayout_sort;
    private List<FoodSortBean.TypesBean> types;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_food_class);
        initData();
        initView();
    }

    private void initData() {
//        获取数据
        Intent intent = getIntent();
        categoriesBean = (FoodBean.GroupBean.CategoriesBean) intent.getExtras().getSerializable(FoodConstant.FOOD_CategoriesBean_KEY);
        kind = intent.getExtras().getString(FoodConstant.FOOD_KIND_KEY);
        id = categoriesBean.getId() + "";
        map.put("kind", kind);
        map.put("value", id);
        map.put("order_by", order_by);
        map.put("page", page);
        map.put("order_asc", order_asc);

        foodClassPresenter = new FoodClassPresenter(this);
        foodClassPresenter.getFoodClassObservable(map);
        foodClassPresenter.getSortObservable(BaseMap.baseMap());
    }

    private void initView() {
        imageView_gif= (ImageView) findViewById(R.id.imageView_gif);
        imageView_gif.setImageDrawable(animationDrawable);
//        设置toolBar
        toolBar_foodClass = (Toolbar) findViewById(R.id.toolBar_foodClass);
        toolBar_foodClass.setTitle(categoriesBean.getName());
        setSupportActionBar(toolBar_foodClass);
        ActionBar supportActionBar = getSupportActionBar();
        supportActionBar.setDisplayHomeAsUpEnabled(true);
//         营养素排序
        imageView_sortDown = (ImageView) findViewById(R.id.imageView_sortDown);
        animatorUp = AnimatorInflater.loadAnimator(mContent, R.animator.sort_rotate_up);
        animatorDown = AnimatorInflater.loadAnimator(mContent, R.animator.sort_rotate_down);
        animatorUp.setTarget(imageView_sortDown);
        animatorDown.setTarget(imageView_sortDown);
        textView_sort = (TextView) findViewById(R.id.textView_sort);
        textView_sort.setOnClickListener(this);
//        顺序
        textView_order = (TextView) findViewById(R.id.textView_order);
        textView_order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isOrder) {
                    textView_order.setText("由高到低↓");
                    order_asc = "0";
                } else {
                    textView_order.setText("由低到高↑");
                    order_asc = "1";
                }
                isOrder = !isOrder;
                map.put("order_asc", order_asc);
                foodClassPresenter.getFoodClassObservable(map);
            }
        });

        recyclerView_foodClass = (RecyclerView) findViewById(R.id.recyclerView_foodClass);
        recyclerView_foodClass.setHasFixedSize(true);
        linearLayoutManager = new LinearLayoutManager(mContent, OrientationHelper.VERTICAL, false);
        recyclerView_foodClass.setLayoutManager(linearLayoutManager);
        foodClassRecAdapter = new FoodClassRecAdapter(mContent, foodsBeanList);
        recyclerView_foodClass.setAdapter(foodClassRecAdapter);
        recyclerView_foodClass.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                int totalItemCount = recyclerView.getAdapter().getItemCount();
                int lastVisibleItemPosition = linearLayoutManager.findLastVisibleItemPosition();
                int childCount = recyclerView.getChildCount();
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItemPosition == totalItemCount - 1
                        && childCount > 0)
                {
//                    加载更多
                    pageNum++;
                    page=pageNum+"";
                    map.put("page",page);
                    foodClassPresenter.getNextFoodClassObservable(map);
                }
            }

        });
    }

    //    设置toolBar的按键点击
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void showProgress() {
//        imageView_gif.setVisibility(View.VISIBLE);
        animationDrawable.start();
    }

    @Override
    public void hideProgress() {
        animationDrawable.stop();
        imageView_gif.setVisibility(View.GONE);
    }

    @Override
    public void loadFoodClassData(FoodClassBean foodClassBean) {
        List<FoodClassBean.FoodsBean> foods = foodClassBean.getFoods();
//        刷新适配器
        foodClassRecAdapter.reloadRecyclerView(foods, true);
    }

    @Override
    public void loadNextFoodClassData(FoodClassBean foodClassBean) {
        List<FoodClassBean.FoodsBean> foods = foodClassBean.getFoods();
        foodsBeanList.addAll(foods);
        foodClassRecAdapter.notifyDataSetChanged();
    }

    @Override
    public void loadSort(FoodSortBean foodSortBean) {
        types = foodSortBean.getTypes();
//        popupWindow
        showPopupWindows();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.textView_sort:
                animatorUp.start();
                popupWindow.showAsDropDown(textView_sort);
                break;
        }
    }

    private void showPopupWindows() {
        view = LayoutInflater.from(mContent).inflate(R.layout.popwindow, null);
        popupWindow = new PopupWindow(view,
                LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.WRAP_CONTENT, true);
//        设置popWin的弹出动画
//        popupWindow.setAnimationStyle(R.style.popWin);
        popupWindow.setTouchable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable(getResources(), (Bitmap) null));
//        监听popupWindow消失
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                animatorDown.start();
            }
        });

        gridLayout_sort = (GridLayout) view.findViewById(R.id.gridLayout_sort);
        for (int i = 0; i < types.size(); i++) {
            final FoodSortBean.TypesBean typesBean = types.get(i);
            final String name = typesBean.getName();
            final TextView textView = new TextView(mContent);
            GridLayout.LayoutParams layoutParams = new GridLayout.LayoutParams();
            layoutParams.width = BaseApplication.width / 3;
            layoutParams.height = layoutParams.width / 3;
            layoutParams.setMargins(5, 5, 5, 5);
            textView.setLayoutParams(layoutParams);
            textView.setGravity(Gravity.CENTER);
            textView.setText(name);
            textView.setTextColor(getResources().getColor(R.color.black));

//            点击改变popWin中textView的状态
            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    for (int j = 0; j < types.size(); j++) {
                        TextView textView = (TextView) gridLayout_sort.getChildAt(j);
                        textView.setTextColor(getResources().getColor(R.color.black));
                        textView.setBackgroundColor(getResources().getColor(R.color.white));
                        textView_sort.setText(name);
                        textView_order.setVisibility(View.VISIBLE);
                    }
                    textView.setTextColor(getResources().getColor(R.color.pinkNum));
                    textView.setBackgroundColor(getResources().getColor(R.color.blueBac));
//                    重新排序
                    order_by = typesBean.getIndex() + "";
                    map.put("order_by", order_by);
//                    popupWindow消失
                    popupWindow.dismiss();
                    foodClassPresenter.getFoodClassObservable(map);
                }
            });
            gridLayout_sort.addView(textView);
        }
    }
}
